<template>
  <a-modal
    title="选择角色"
    :dialogStyle="{top:'10px'}"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @cancel="handleCancel"
    @ok="handleSubmit"
  >
    <a-checkbox-group v-model="roles">
      <a-row :gutter="20">
        <a-col v-for="role in rolesOptions" :key="role.roleId" :span="8">
          <a-checkbox :value="role.roleId">{{ role.roleName }}</a-checkbox>
        </a-col>
      </a-row>
    </a-checkbox-group>
  </a-modal>
</template>

<script>
import { getRoleList } from '@/api/role'
import { authorizeByUserId, getUserRolesByUserId } from '@/api/user'

export default {
  name: 'RoleInfo',
  props: {
    info: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      confirmLoading: false,
      rolesOptions: [],
      visible: false,
      roles: []
    }
  },
  created () {
    this.visible = true
    // 所有角色
    getRoleList().then(response => {
      this.rolesOptions = response.data
    })

    // 用户的角色
    this.$nextTick(() => {
      getUserRolesByUserId(this.info.userId).then(response => {
        this.roles = response.data.map(k => k.roleId)
      })
    })
  },
  methods: {
    handleSubmit () {
      this.confirmLoading = true
      authorizeByUserId(this.info.userId, this.roles).then(() => {
        this.$message.success('授权成功')
        this.handleCancel(false)
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    handleCancel (isRef) {
      this.visible = false
      this.$emit('close', isRef)
    }
  }
}
</script>

<style scoped>

</style>
